<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use App\Repositories\GamerRepository;
use App\Repositories\GameServer\LoginRecordRepository;
use App\Repositories\GameServer\PlayRecordRepository;
use App\Repositories\GameServer\RechargeRecordRepository;
use App\Repositories\GameServer\ChannelRepository;

class StatisticsController extends Controller
{
    protected $Gamer;
    protected $LoginRecord;
    protected $PlayRecord;
    protected $RechargeRecord;
    protected $Channel;

    public function __construct(GamerRepository $gamer,LoginRecordRepository $loginRecord,PlayRecordRepository $playRecord,RechargeRecordRepository $rechargeRecord,ChannelRepository $channel)
    {
        $this->middleware('admin.auth');

        $this->Gamer = $gamer;
        $this->LoginRecord = $loginRecord;
        $this->PlayRecord = $playRecord;
        $this->RechargeRecord = $rechargeRecord;
        $this->Channel = $channel;
    }

    public function index(Request $request)
    {
        $data = $request->all();
        // dd($data);
        $date = $request->date;
        $channel = $request->channel;

        if (!empty($date)) {
            $time = explode('~', $date);
            $start = Carbon::parse($time[0]);
            $end = Carbon::parse($time[1]);
        } else {
            $start = Carbon::today()->subDays(6);
            $end = Carbon::today();
        }

        //如果 == NULL 即获取全部渠道
        if ($channel === NULL || stripos($channel, 'all') !== false) {
            $channel = false;
        } else {
            $channel = explode(',', $channel);
        }

        $where = [];
        $where['start'] = $start->timestamp;
        $where['end'] = $end->timestamp;
        $where['channel'] = $channel;

        $channels = $this->getChannels($channel);//渠道商
        $channels_arr = array_column($channels, 'realname');
        $channels_str = implode(',', $channels_arr);

        $new_gamers = $this->getNewGamer($where);//新增
        $active_gamers = $this->getActiveGamer($where);//活跃
        $timezone = $this->getDateFromRange($start, $end);//时间期间
        $valid_active_gamers = $this->getValidActiveGamer($where);//有效活跃
        $pay_gamers = $this->getPayGamer($where);//付费用户
        $pay_amount = $this->getPayAmount($where);//付费金额
// dd($timezone);
// dd($channels);
// dump($new_gamers);
// dump($active_gamers);
        $res = [];
        foreach ($timezone as $time) {
            foreach ($channels as $channel) {
                $distributer_id = $channel['distributer_id'];

                $data = [];
                $data['date']         = $time;
                $data['channel']      = $channel['realname'];
                $data['new']          = $this->filterData($time, $distributer_id, $new_gamers);
                $data['active']       = $this->filterData($time, $distributer_id, $active_gamers);
                $data['valid_active'] = $this->filterData($time, $distributer_id, $valid_active_gamers);
                $data['pay']          = $this->filterData($time, $distributer_id, $pay_gamers);
                $data['pay_amount']   = $this->filterData($time, $distributer_id, $pay_amount);

                $data['pay_rate']     = $this->getPayRate($data['pay'], $data['active']);
                $data['arpu']         = $this->getArpu($data['pay_amount'], $data['active']);
                $data['arppu']        = $this->getArppu($data['pay_amount'], $data['pay']);
                $data['retention_rate'] = $this->getSecondRetentionRate($time, $distributer_id);

                $res[] = $data;
            }
        }
        // dump($new_gamers);
        // dump($active_gamers);
        // dump($res);

        $channels = $this->getChannels();

        return view('admin.statistics.index', compact('channels','res','date','channels_str'));


    }

    public function filterData($time, $distributer_id, &$arr)
    {
        foreach ($arr as $key => $val) {
            if ($time == $val['date'] && $distributer_id == $val['distributer_id']) {
                $num = $val['count'];
                unset($arr[$key]);
                return $num;
            }
        }
        return 0;
    }

    //获取渠道
    public function getChannels($where = null)
    {
        $channels = $this->Channel->getChannels($where)->toArray();
        // dd($channels);
        return $channels;
    }

    //新增用户
    public function getNewGamer($where)
    {
        $gamers = $this->Gamer->getNewGamerOfChannel($where)->toArray();
        // dd($gamers);
        return $gamers;
    }

    //活跃用户
    public function getActiveGamer($where)
    {
        $gamers = $this->LoginRecord->getActiveGamerOfChnnel($where)->toArray();
        // dd($gamers);
        return $gamers;
    }

    //有效用户
    public function getValidActiveGamer($where)
    {
        $gamers = $this->PlayRecord->getValidActiveGamerOfChannel($where)->toArray();
        // dd($gamers);
        return $gamers;
    }

    //付费用户
    public function getPayGamer($where)
    {
        $gamers = $this->RechargeRecord->getPayGamerOfChannel($where)->toArray();
        // dd($gamers);
        return $gamers;
    }

    //付费总额
    public function getPayAmount($where)
    {
        $gamers = $this->RechargeRecord->getRechargeAmountOfChannel($where)->toArray();
        // dd($gamers);
        return $gamers;
    }

    //付费率 = 付费用户 / 活跃用户
    public function getPayRate($pay, $active)
    {
        $rate = $active > 0 ? round($pay / $active, 4) : 0;

        return sprintf('%.2f', $rate*100) . '%';
    }

    //ARPU = 付费总额 / 活跃用户
    public function getArpu($amount, $active)
    {
        $arpu = $active > 0 ? round($amount / $active, 2) : 0.0;

        return $arpu;
    }

    //ARPPU = 付费总额 / 付费用户
    public function getArppu($amount, $pay)
    {
        $arppu = $pay > 0 ? round($amount / $pay, 2) : 0.0;

        return $arppu;
    }

    //次日留存率 = 今日活跃人数 / 昨日注册人数
    public function getSecondRetentionRate($time, $distributer_id)
    {
        $today = Carbon::parse($time);
        $yesterday = Carbon::parse($time)->subDay();

        $where = [];
        $where['channel'] = $distributer_id;
        $where['start'] = $yesterday->timestamp;
        $where['end'] = $today->timestamp;

        $yesterday_reg = $this->Gamer->getNewGamer($where);
        $reg_num = $yesterday_reg->count();//注册人数
        $reg_ids = $yesterday_reg->pluck('id')->all();

        if ($reg_num > 0) {
            $where['start'] = $today->timestamp;
            $where['end'] = $today->addDay()->timestamp;
            $where['ids'] = $reg_ids;

            $today_login_num = $this->LoginRecord->getLogin($where)->count();//登录人数

            $rate = (round($today_login_num / $reg_num, 4) * 100) .'%';

            return $today_login_num . ' (' . $rate . ')';
        }

        return '0(0%)';
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */
     public function getDateFromRange($startdate, $enddate)
    {
        while ($startdate->timestamp <= $enddate->timestamp) {
            $date[] = $startdate->toDateString();

            $startdate->addDay();
        }
        rsort($date);

        return $date;
    }
}
